package com.zhixiang.core.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class CertUtil
{
    public static Log logger = LogFactory.getLog(CertUtil.class);

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    public static File get(String s, int i)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException
    {
        char[] ac = "changeit".toCharArray();
        File file = new File("jssecacerts");
        if (!file.isFile())
        {
            char c = File.separatorChar;
            File file1 = new File(System.getProperty("java.home") + c + "lib" + c + "security");
            file = new File(file1, "jssecacerts");
            if (!file.isFile()) file = new File(file1, "cacerts");
        }
        FileInputStream fileinputstream = new FileInputStream(file);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(fileinputstream, ac);
        fileinputstream.close();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustmanagerfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustmanagerfactory.init(keystore);
        X509TrustManager x509trustmanager = (X509TrustManager)trustmanagerfactory.getTrustManagers()[0];
        SavingTrustManager savingtrustmanager = new SavingTrustManager(x509trustmanager);
        sslcontext.init(null, new TrustManager[] {savingtrustmanager}, null);
        SSLSocketFactory sslsocketfactory = sslcontext.getSocketFactory();
        logger.debug("Opening connection to " + s + ":" + i + "...");
        SSLSocket sslsocket = (SSLSocket)sslsocketfactory.createSocket(s, i);
        sslsocket.setSoTimeout(10000);
        if (sslsocket != null)
        {
            sslsocket.startHandshake();
            sslsocket.close();
        }
        X509Certificate[] ax509certificate = savingtrustmanager.chain;
        if (ax509certificate == null) return null;
        try
        {
            MessageDigest messagedigest = MessageDigest.getInstance("SHA1");
            MessageDigest messagedigest1 = MessageDigest.getInstance("MD5");
            for (int j = 0; j < ax509certificate.length; j++ )
            {
                X509Certificate x509certificate = ax509certificate[j];
                messagedigest.update(x509certificate.getEncoded());
                messagedigest1.update(x509certificate.getEncoded());
            }

            int k = 1;
            X509Certificate x509certificate1 = ax509certificate[k];
            String s1 = s + "-" + (k + 1);
            keystore.setCertificateEntry(s1, x509certificate1);
            File file2 = new File("jssecacerts");
            FileOutputStream fileoutputstream = new FileOutputStream(file2);
            keystore.store(fileoutputstream, ac);
            fileoutputstream.close();
            logger.debug("Added certificate to keystore 'jssecacerts' using alias '" + s1 + "'");
            return file2;
        }
        catch (SSLException sslexception)
        {
            logger.debug("明文连接,javax.net.ssl.SSLException:" + sslexception.getMessage());
            return null;
        }
        catch (KeyStoreException keystoreexception)
        {
            keystoreexception.printStackTrace();
            return null;
        }
        catch (FileNotFoundException filenotfoundexception)
        {
            filenotfoundexception.printStackTrace();
            return null;
        }
        catch (NoSuchAlgorithmException nosuchalgorithmexception)
        {
            nosuchalgorithmexception.printStackTrace();
            return null;
        }
        catch (CertificateException certificateexception)
        {
            certificateexception.printStackTrace();
            return null;
        }
        catch (IOException ioexception)
        {
            ioexception.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("unused")
    private static String toHexString(byte[] abyte0)
    {
        StringBuilder stringbuilder = new StringBuilder(abyte0.length * 3);
        byte[] abyte1 = abyte0;
        int i = abyte1.length;
        for (int j = 0; j < i; j++ )
        {
            int k = abyte1[j];
            k &= 255;
            stringbuilder.append(HEXDIGITS[(k >> 4)]);
            stringbuilder.append(HEXDIGITS[(k & 0xF)]);
            stringbuilder.append(' ');
        }

        return stringbuilder.toString();
    }

    private static class SavingTrustManager implements X509TrustManager
    {
        private final X509TrustManager tm;

        private X509Certificate[] chain;

        public X509Certificate[] getAcceptedIssuers()
        {
            throw new UnsupportedOperationException();
        }

        public void checkClientTrusted(X509Certificate[] ax509certificate, String s)
            throws CertificateException
        {
            throw new UnsupportedOperationException();
        }

        public void checkServerTrusted(X509Certificate[] ax509certificate, String s)
            throws CertificateException
        {
            this.chain = ax509certificate;
            this.tm.checkServerTrusted(ax509certificate, s);
        }

        SavingTrustManager(X509TrustManager x509trustmanager)
        {
            this.tm = x509trustmanager;
        }
    }
}
